<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :width="1200"
    :height="600"
    title="历史转发"
    @ok="historyResend"
    :helpMessage="['请先搜索,在进行转发']"
  >
    <a-form
      ref="queryFormRef"
      class="antd-modal-form"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
      :rules="validatorRules"
      :model="queryParam"
      name="ClueRecordForm"
    >
      <a-row>
        <a-col :span="24">
          <a-form-item name="source">
            <template #label><span title="线索来源">线索来源</span></template>
            <j-select-user
              isRadioSelection
              placeholder="请选择线索来源"
              v-model:value="queryParam.source"
              @change="(value) => handleFormJoinChange('source', value)"
              allow-clear
            />
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item name="createTime">
            <template #label><span title="创建时间范围">时间范围</span></template>
            <a-space size="large">
              <a-range-picker value-format="YYYY-MM-DD HH:mm:ss" v-model:value="queryParam.createTime" />
              <a-button type="primary" :loading="historySearchLoading" @click="onSearch">搜索 </a-button>
            </a-space>
          </a-form-item>
        </a-col>
        <a-divider><span style="font-weight: bold">转发</span></a-divider>
        <a-col :span="24">
          <a-table
            :loading="historySearchLoading"
            size="middle"
            :row-selection="rowSelection"
            rowKey="id"
            :dataSource="dataSource"
            :columns="columns"
          >
          </a-table>
        </a-col>
        <a-col :span="24">
          <a-form-item label="转发平台" name="resendTpCarId">
            <a-select ref="select" v-model:value="queryParam.resendTpCarId" style="width: 20vw" @focus="resendTpCarIdFocus">
              <a-select-option v-for="item in userTpCarList" :key="item.tpCarId" :value="item.tpCarId"> {{ item.name }} </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </BasicModal>
</template>
<script setup lang="ts">
  import { reactive, ref, toRaw } from 'vue';
  import JSelectUser from '../../../../components/Form/src/jeecg/components/JSelectUser.vue';
  import { historyResendPost, historySearch } from '@/views/clue/clueRecord/ClueRecord.api';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { message } from 'ant-design-vue';
  import JDictSelectTag from '../../../../components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { userTpCarRelateListByUsername } from '@/views/clue/tpCarConfig/ClueTpCarConfig.api';

  const [register, { closeModal, setModalProps ,changeOkLoading}] = useModalInner();

  const queryFormRef = ref();
  const rowSelection = reactive({
    onChange: (selectedRowKeys, selectedRows) => (rowSelection.selectedRowKeys = selectedRowKeys),
    selectedRowKeys: [],
  });

  const queryParam = reactive({
    source: '',
    createTime: '',
    phoneList: '',
    resendTpCarId: '',
  });

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      align: 'center',
      customRender: ({ text, record, index }) => `${index + 1}`,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '记录号',
      dataIndex: 'recordNo',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
    },
    {
      title: '城市',
      dataIndex: 'city',
    },
    {
      title: '录入方式',
      dataIndex: 'writeMode',
    },
  ];

  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });

  //表单验证

  const validatorRules = {
    source: [{ required: true, message: '请选择线索来源!', trigger: 'change' }],
    createTime: [{ required: true, message: '请选择时间范围!', trigger: 'change' }],
  };

  const historySearchLoading = ref(false);
  const dataSource = reactive([]);
  const onSearch = async () => {
    queryFormRef.value
      .validate()
      .then(() => {
        console.log('values', queryParam, toRaw(queryParam));
        historySearchLoading.value = true;
        dataSource.splice(0, dataSource.length);
        historySearch({
          source: queryParam.source,
          startCreateTime: queryParam.createTime[0],
          endCreateTime: queryParam.createTime[1],
        })
          .then((res) => {
            dataSource.splice(0, dataSource.length, ...res);
            rowSelection.selectedRowKeys = res.map((item) => item.id);
          })
          .finally(() => {
            historySearchLoading.value = false;
          });
      })
      .catch((error) => {
        console.log('error', error);
      });
  };

  const userTpCarList = reactive([]);
  const resendTpCarIdFocus = () => {
    if (!queryParam.source) {
      message.warning('请先选择用户');
      return;
    }

    userTpCarRelateListByUsername({ username: queryParam.source }).then((res) => {
      userTpCarList.splice(0, userTpCarList.length, ...res.filter((item) => item.tpCarConfigId == item.tpCarId));
    });
  };


  const historyResend = () => {
    if (rowSelection.selectedRowKeys.length == 0) {
      message.warning('请选择转发记录');
      return;
    }
    if (!queryParam.resendTpCarId) {
      message.warning('请选择转发平台');
      return;
    }
    if (!queryParam.source) {
      message.warning('请选择用户');
      return;
    }
    changeOkLoading(true)
    historyResendPost({
      source: queryParam.source,
      tagAreaConfigId: queryParam.resendTpCarId,
      cludRecordIdList: rowSelection.selectedRowKeys,
    }).then((res) => {
      if (200 == res.code) {
        message.success(res.message)

      }else{
        message.error(res.message)
      }
    }).finally(()=>{
      changeOkLoading(false)
    })
  };

  /**
   * form点击事件(以逗号分割)
   * @param key
   * @param value
   */
  function handleFormJoinChange(key, value) {
    if (typeof value != 'string') {
      queryParam[key] = value.join(',');
    }
    rowSelection.selectedRowKeys = [];
    dataSource.splice(0, dataSource.length);
  }
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
